package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.util.DESUtil;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.ChengYiRongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class ChengYiRongReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String apiKey = sourceBaseInfo.getApiKey();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String channelCode = jsonObjectParamContent.getString("channelCode");
        if (!apiKey.equals(channelCode)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的渠道编号不符"));
            return sourceApiResult;
        }

        String data = jsonObjectParamContent.getString("data");
        String paramContentData = DESUtil.decrypt(apiSecret, data);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("requestId")) || StrUtil.isEmpty(jsonObject.getString("userName")) || StrUtil.isEmpty(jsonObject.getString("sex")) || StrUtil.isEmpty(jsonObject.getString("md5Phone")) || jsonObject.getInteger("age") == null || jsonObject.getInteger("education") == null ||
        jsonObject.getInteger("city") == null || jsonObject.getInteger("loanAmt") == null || jsonObject.getInteger("loanTerm") == null || jsonObject.getInteger("loanUse") == null ||
        jsonObject.getInteger("social") == null || jsonObject.getInteger("fund") == null || jsonObject.getInteger("insurance") == null ||
        jsonObject.getInteger("car") == null || jsonObject.getInteger("house") == null || jsonObject.getInteger("profession") == null || jsonObject.getInteger("businessLicense") == null ||
        jsonObject.getInteger("creditLimit") == null || jsonObject.getInteger("overdue") == null || jsonObject.getInteger("zhima") == null || jsonObject.getInteger("incomeMonth") == null ||
        jsonObject.getInteger("salaryType") == null){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("data");
        String paramContentData = DESUtil.decrypt(apiSecret, content);

        ChengYiRongParam chengYiRongParam = JSON.parseObject(paramContentData, ChengYiRongParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(chengYiRongParam.getPhone());
        userDataParam.setRealName(chengYiRongParam.getUserName());

        String productId = chengYiRongParam.getRequestId();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "操作成功！");
        JSONObject dataObject = new JSONObject();
        dataObject.put("status",1);
        dataObject.put("message","撞库成功");

        dataObject.put("price", pushResultInfo.getPriceAmount());
        dataObject.put("settlementPrice", 0.00);
        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }
            dataObject.put("productName", thirdBaseInfo.getProductName());
        }else {
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("productName", merchantBaseInfo.getInfoName());
        }
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status",1);
                jsonObject.put("message","进件成功");
                returnObject.put("data",jsonObject);
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("进件失败");
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "操作成功");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status",0);
        jsonObject.put("message",message);

        returnObject.put("data", jsonObject);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "操作成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        ChengYiRongParam chengYiRongParam = JSON.parseObject(paramContent, ChengYiRongParam.class);

        UserDataParam userDataParam = new UserDataParam();

        userDataParam.setOutOrderNo(chengYiRongParam.getRequestId());

        userDataParam.setMobileMd5(chengYiRongParam.getMd5Phone());
        userDataParam.setMobile(chengYiRongParam.getPhone());
        userDataParam.setRealName(chengYiRongParam.getUserName());

        if ("男".equals(chengYiRongParam.getSex())){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }


        userDataParam.setAge(chengYiRongParam.getAge());
        userDataParam.setCityCode(String.valueOf(chengYiRongParam.getCity()));


        Integer creditCardLimit = chengYiRongParam.getCreditLimit();
        if (creditCardLimit == 5){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        Integer loanUse = chengYiRongParam.getLoanUse();
        if (loanUse == 1){
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt003.getValue());
        }else if (loanUse == 2){
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt002.getValue());
        }else if (loanUse == 3){
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt004.getValue());
        }else if (loanUse == 4){
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt005.getValue());
        }else if (loanUse == 5){
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt001.getValue());
        }else{
            userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        }

        Integer education = chengYiRongParam.getEducation();
        if (education == -1){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }else if (education == 0){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl002.getValue());
        }else if (education == 1){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl003.getValue());
        }else if (education == 2){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
        }else {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl005.getValue());
        }

        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());

        String ip = chengYiRongParam.getIp();
        if (StringUtils.isNotEmpty(ip)){
            userDataParam.setUserIp(ip);
        }else {
            userDataParam.setUserIp("127.0.0.1");
        }

        Integer loan = chengYiRongParam.getLoanAmt();
        if (loan <= 3) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (loan > 3 && loan <= 5) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (loan > 5 && loan <= 10) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (loan >10 && loan <= 20) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        Integer houseProperty = chengYiRongParam.getHouse();
        if (houseProperty == 2){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else if (houseProperty == 13){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu004.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }

        Integer insurance = chengYiRongParam.getInsurance();
        if (insurance == 1){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx003.getValue());
        }


        Integer overdue = chengYiRongParam.getOverdue();
        if (overdue == 0){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else if (overdue == 1 || overdue == 2){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }else {
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
        }

        Integer hasFund = chengYiRongParam.getFund();
        if (hasFund == 0){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if (hasFund == 1){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        Integer zhimaCredit = chengYiRongParam.getZhima();
        if (zhimaCredit == 5){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if (zhimaCredit == 4){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if (zhimaCredit == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        Integer hasSocial = chengYiRongParam.getSocial();
        if (hasSocial == 0){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if (hasSocial == 1){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        Integer carProperty = chengYiRongParam.getCar();
        if (carProperty == 1){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else if (carProperty == 2){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        Integer professional = chengYiRongParam.getProfession();
        if (professional == 1 || professional == 7){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if (professional == 5){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (professional == 4){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }if (professional == 9){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        Integer loanTerm = chengYiRongParam.getLoanTerm();
        if (loanTerm == 6 || loanTerm == 7 || loanTerm == 8){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt004.getValue());
        }else if (loanTerm == 4 || loanTerm == 5){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else if (loanTerm == 2 || loanTerm == 3){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt002.getValue());
        }else {
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        }


        return userDataParam;
    }

}
